﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZhonTai.Admin.Core.Dto;
using ZhonTai.Admin.Services;
using ZhonTai.DynamicApi;
using ZhonTai.DynamicApi.Attributes;
using ZhonTai.Industry.Core.Consts;
using ZhonTai.Industry.Domain.DeviceFormula;
using ZhonTai.Industry.Domain.FormulaDetail;
using ZhonTai.Industry.Services.DeviceFormula.Dto.Input;
using ZhonTai.Industry.Services.DeviceFormula.Dto.Output;
using ZhonTai.Industry.Services.WorkStation.Dto.Input;

namespace ZhonTai.Industry.Services.DeviceFormula
{
    /// <summary>
    /// 设备配方服务
    /// </summary>
    [Order(20)]
    [DynamicApi(Area = IndustryConsts.AreaName)]
    public class DeviceFormulaService : BaseService, IDeviceFormulaService, IDynamicApi
    {
        private readonly IDeviceFormulaRepository _deviceFormulaRepository;

        public readonly IFormulaDetailRepository _formulaDetailRepository;

        public DeviceFormulaService(
            IDeviceFormulaRepository deviceFormulaRepository,
            IFormulaDetailRepository formulaDetailRepository)
        {
            _deviceFormulaRepository = deviceFormulaRepository;
            _formulaDetailRepository = formulaDetailRepository;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<DeviceFormulaGetOutput> GetAsync(long id)
        {
            var a = await _deviceFormulaRepository.Select
                .WhereDynamic(id)
                .ToOneAsync<DeviceFormulaGetListOutput>();
            return a;
        }

        /// <summary>
        /// 列表查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IEnumerable<DeviceFormulaGetListOutput>> GetListAsync(DeviceFormulaGetListInput input)
        {
            var list = await _deviceFormulaRepository.Select
                .OrderBy(a => a.Sort)
                .ToListAsync<DeviceFormulaGetListOutput>();
            return list;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<DeviceFormulaGetPageOutput>> GetPageAsync(PageInput<DeviceFormulaGetPageInput> input)
        {
            var filter = input.Filter;
            var select = _deviceFormulaRepository.Select
                .WhereDynamicFilter(input.DynamicFilter)
                .Count(out var total);
            if (input.SortList != null && input.SortList.Count > 0)
            {
                input.SortList.ForEach(sort =>
                {
                    select = select.OrderByPropertyNameIf(sort.Order.HasValue, sort.PropName, sort.IsAscending.Value);
                });
            }
            else
            {
                select = select.OrderBy(a => a.Sort);
            }
            var list = await select
            .Page(input.CurrentPage, input.PageSize)
            .ToListAsync<DeviceFormulaGetPageOutput>();
            var data = new PageOutput<DeviceFormulaGetPageOutput>()
            {
                List = list,
                Total = total
            };
            return data;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<long> AddAsync(DeviceFormulaAddInput input)
        {
            var entity = Mapper.Map<DeviceFormulaEntity>(input);
            var id = (await _deviceFormulaRepository.InsertAsync(entity)).Id;

            return id;
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task UpdateAsync(DeviceFormulaUpdateInput input)
        {
            var entity = await _deviceFormulaRepository.GetAsync(input.Id);
            if (!(entity?.Id > 0))
            {
                throw ResultOutput.Exception("产品路线详情不存在！");
            }

            Mapper.Map(input, entity);
            await _deviceFormulaRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<bool> DeleteAsync(long id)
        {
            await _formulaDetailRepository.SoftDeleteRecursiveAsync(s=>s.DeviceFormulaId==id);
            return await _deviceFormulaRepository.DeleteAsync(id) > 0;
        }

        /// <summary>
        /// 软删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<bool> SoftDeleteAsync(long id)
        {
            return await _deviceFormulaRepository.SoftDeleteAsync(id);
        }

        /// <summary>
        /// 批量软删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<bool> BatchSoftDeleteAsync(long[] ids)
        {
            return await _deviceFormulaRepository.SoftDeleteAsync(ids);
        }

        /// <summary>
        /// 设置启用
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task SetEnableAsync(DeviceFormulaSetEnableInput input)
        {
            var entity = await _deviceFormulaRepository.GetAsync(input.DeviceFormulaId);
            entity.Enabled = input.Enabled;
            await _deviceFormulaRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 关联点位启用
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task SetLinkPointEnableAsync(DeviceFormulaSetLinkPointInput input)
        {
            var entity = await _deviceFormulaRepository.GetAsync(input.DeviceFormulaId);
            entity.Enabled = input.LinkPointEnaled;
            await _deviceFormulaRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 复制配方
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task CopyDeviceFormulaAsync(DeviceFormulaCopyInput input)
        {
            DeviceFormulaEntity? entity = Mapper.Map<DeviceFormulaEntity>(input);
            if (entity == null)
            {
                throw new Exception("复制配方参数为空!");
            }
            var formuladeviceId = (await _deviceFormulaRepository.InsertAsync(entity)).Id;
            if (input.CopyFormulaDetail)
            {
                var formulaDetailList = await _formulaDetailRepository.Select
                    .Where(w => w.DeviceFormulaId == input.CopyDeviceFormulaId)
                    .ToListAsync(t => new FormulaDetailEntity()
                    {
                        StationId = t.StationId,
                        DeviceFormulaId = formuladeviceId,
                        OffsetId = t.OffsetId,
                        ParamKey = t.ParamKey,
                        ParamValue = t.ParamValue,
                        Sort = t.Sort,
                        Enabled = t.Enabled,
                    });
                await _formulaDetailRepository.InsertAsync(formulaDetailList);
            }
        }
    }
}